package com.qj.sys.db.sysuser;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.qj.sys.db.entity.BackUpDataSceneEnum;
import com.qj.sys.db.handler.AbstractBackUpDataHandler;
import com.qj.sys.entity.SysUser;
import com.qj.sys.mapper.SysUserBackMapper;
import com.qj.sys.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dlw
 * @date 2025-06-03 11:38
 */
@Slf4j
@Component
public class SysUserForwardHandler extends AbstractBackUpDataHandler<SysUser, SysUserBackUpDataRule> {

    /**
     * 归档规则，可以配合nacos动态配置
     * (设置为String格式的json，与SysUserBackUpDataRule中的参数一一对应)
     */
    private String sysUserBackupRuleStr = "{\"beginId\":1,\"querySize\":10}";

    /**
     * 佣金系数归档停止flag，可以配合nacos动态配置
     * (可以随时停止归档)
     */
    private Boolean stopFlag = false;

    @Resource
    private SysUserMapper sysUserDao;

    @Resource
    private SysUserBackMapper sysUserBackDao;

    @Override
    public Boolean needStop() {
        return stopFlag;
    }

    /**
     * 场景定义
     */
    @Override
    public BackUpDataSceneEnum getScene() {
        return BackUpDataSceneEnum.USER_FORWARD;
    }

    /**
     * 查询数据
     */
    @Override
    public List<SysUser> queryData(SysUserBackUpDataRule rule) {
        SysUser sysUser = new SysUser();
        List<SysUser> sysUserList = sysUserDao.queryAll(sysUser);
        return sysUserList;
    }

    /**
     * 插入数据
     */
    @Override
    public void insertData(List<SysUser> sysUserList) {
        int i = sysUserBackDao.insertBatch(sysUserList);
    }

    /**
     * 删除数据
     */
    @Override
    public void deleteData(List<SysUser> dataList) {
        List<Long> ids = dataList.stream().map(SysUser::getId).collect(Collectors.toList());
        int i = sysUserDao.batchDelete(ids);
    }

    /**
     * 归档规则
     */
    @Override
    public SysUserBackUpDataRule getRule() {
        SysUserBackUpDataRule backUpRule = JSON.parseObject(sysUserBackupRuleStr, SysUserBackUpDataRule.class);


        Preconditions.checkNotNull(backUpRule, "归档规则不能为空！");
        Preconditions.checkNotNull(backUpRule.getQuerySize(), "查询数量不能为空！");
        Preconditions.checkNotNull(backUpRule.getBeginId(), "beginId不能为空！");
        Long endId = backUpRule.getBeginId() + backUpRule.getQuerySize();
        backUpRule.setEndId(endId);
        return backUpRule;
    }

    /**
     * 归档偏移量变更
     */
    @Override
    public SysUserBackUpDataRule changeOffSet(SysUserBackUpDataRule backupDataRule) {
        backupDataRule.setBeginId(backupDataRule.getEndId());
        Long endId = backupDataRule.getBeginId() + backupDataRule.getQuerySize();
        backupDataRule.setEndId(endId);
        return backupDataRule;
    }
}
